<?php

namespace app\model;

use think\Model;

class UserDevice extends Model
{
    // 表名
    protected $name = 'user_devices';

    // 自动时间戳
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 字段类型转换
    protected $type = [
        'device_info' => 'json',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'last_active' => 'datetime',
    ];

    // 关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // 通过设备ID查找
    public static function findByDeviceId($deviceId)
    {
        return self::where('device_id', $deviceId)->find();
    }

    // 检查用户设备数量限制
    public static function checkUserDeviceLimit($userId, $limit = 10)
    {
        $count = self::where('user_id', $userId)->count();
        return $count < $limit;
    }

    // 更新设备活跃时间
    public function updateActive($ip = null, $userAgent = null)
    {
        $this->last_active = date('Y-m-d H:i:s');
        if ($ip) {
            $this->ip_address = $ip;
        }
        if ($userAgent) {
            $this->user_agent = $userAgent;
        }
        return $this->save();
    }

    // 获取设备平台名称
    public function getPlatformNameAttr()
    {
        $platforms = [
            'h5' => 'H5网页',
            'wechat' => '微信小程序',
            'alipay' => '支付宝小程序',
            'douyin' => '抖音小程序',
        ];
        return $platforms[$this->platform] ?? $this->platform;
    }

    // 获取设备信息显示
    public function getDeviceDisplayAttr()
    {
        $info = $this->device_info;
        if (!$info) {
            return $this->device_name ?: '未知设备';
        }

        $display = [];
        if (isset($info['brand'])) {
            $display[] = $info['brand'];
        }
        if (isset($info['model'])) {
            $display[] = $info['model'];
        }
        if (isset($info['system'])) {
            $display[] = $info['system'];
        }

        return implode(' ', $display) ?: ($this->device_name ?: '未知设备');
    }

    // 清理长时间未活跃的设备
    public static function cleanInactiveDevices($days = 90)
    {
        $cutoffTime = date('Y-m-d H:i:s', time() - $days * 24 * 3600);
        return self::where('last_active', '<', $cutoffTime)->delete();
    }
}